package com.neaten.functionArrangement.controller;

import com.neaten.functionArrangement.common.Result;
import com.neaten.functionArrangement.util.QRCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/util")
@Api(tags = "工具类")
public class UtilController {
    @ApiOperation(value = "测试", notes = "测试1")
    @GetMapping("/test")
    public Result test() {
        System.out.println("test");
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            throw new RuntimeException("出现错误");
        }
        return Result.success("成功", 10);
    }


    @ApiOperation(value = "根据content生成二维码，返回base64格式", notes = "根据content生成二维码，返回base64格式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "二维码内容", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "logoUrl", value = "logo链接", required = false, dataType = "String", paramType = "query")
    })
    @GetMapping("/getQRCodeBase64")
    public Result getQRCode(@RequestParam("content") String content,
                            @RequestParam(value = "logoUrl", required = false) String logoUrl) {
        return Result.success(QRCodeUtil.getBase64QRCode(content, logoUrl));
    }


    @ApiOperation(value = "根据content生成二维码，写入response", notes = "根据content生成二维码，写入response")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "二维码内容", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "logoUrl", value = "logo链接", required = false, dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/getQRCode")
    public Result getQRCode(HttpServletResponse response,
                            @RequestParam("content") String content,
                            @RequestParam(value = "logoUrl", required = false) String logoUrl) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            QRCodeUtil.getQRCode(content, logoUrl, stream);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
        return Result.success();
    }
}
